package com.xyauto.uilib.colorpicker;

import android.annotation.DrawableRes;
import android.annotation.Nullable;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.Button;


import com.xyauto.uilib.R;


/**
 * created by gongziyi on 2023/10/24 14:49
 */
public class BitColorButtonView extends Button implements IBitmapColor {

    private static final String TAG = "BitColorImageView";
    private static final int INVALID_ID = 0;

    private final boolean isInstantly;
    // 渐变角度 0~360
    private final int mAngle;
    // 是否支持background变色 默认关闭
    private final boolean isSupportBackground;
    // 默认变色层
    private final int defaultLayer;

    // background 选中状态\点击状态支持 默认空（全状态换色）、有值时（仅支持值内属性换色）
    private int[] supportBackgroundState;

    private int[] supportTextState;


    private int bgResId;

    private final BitColor bitColor;


    public BitColorButtonView(Context context) {
        this(context, null);
    }

    public BitColorButtonView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BitColorButtonView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BitColorButtonView);
        bitColor = new BitColor(context, a.getBoolean(R.styleable.BitColorButtonView_isList, false),a.getBoolean(R.styleable.BitColorButtonView_supportGradient,false));

        isInstantly = a.getBoolean(R.styleable.BitColorButtonView_isInstantly, false);
        isSupportBackground = a.getBoolean(R.styleable.BitColorButtonView_supportBackground, true);
        mAngle = a.getInteger(R.styleable.BitColorButtonView_gradientAngle, 0);
        defaultLayer = a.getInteger(R.styleable.BitColorButtonView_defaultLayer, 0);
        boolean onlyBackgroundClick = a.getBoolean(R.styleable.BitColorButtonView_onlyBackgroundClick, false);
        boolean onlyTextClick = a.getBoolean(R.styleable.BitColorButtonView_onlyTextClick, false);
        if (a.hasValue(R.styleable.BitColorButtonView_android_background)) {
            bgResId = a.getResourceId(R.styleable.BitColorButtonView_android_background, INVALID_ID);
        }
        a.recycle();
        if (onlyBackgroundClick) {
            supportBackgroundState = new int[]{android.R.attr.state_pressed, android.R.attr.state_selected};
        }
        if (onlyTextClick) {
            supportTextState = new int[]{android.R.attr.state_pressed, android.R.attr.state_selected};
        }
    }


    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        changeColor(BitmapColorHelper.findColour());
        BitmapColorHelper.getInstance().registerContentObserver(this, isInstantly);
    }

    @Override
    protected void onDetachedFromWindow() {
        BitmapColorHelper.getInstance().unregisterContentObserver(this);
        super.onDetachedFromWindow();
    }

    @Override
    public void setBackgroundResource(@DrawableRes int resId) {
        bgResId = resId;
        //ViewCompat.setBackground(this, ContextCompat.getDrawable(getContext(), resId));
        if (resId!=0){
            setBackgroundDrawable(getSkinDrawable(resId));
            // ViewCompat.setBackground(this, ContextCompat.getDrawable(getContext(), resId));
        }else {
            super.setBackgroundResource(0);
        }
    }


    public void applySkin() {
        if (bgResId != INVALID_ID) {
            //ViewCompat.setBackground(this, ContextCompat.getDrawable(getContext(), bgResId));
            setBackgroundDrawable(getSkinDrawable(bgResId));
        }

    }

    private Drawable getSkinDrawable(int res) {
        return   BitmapColorHelper.getInstance().loadResDrawable(getContext(), res);
    }

    @Override
    public void changeColor(ColorParams params) {
        if (bitColor.loadColorParams(params)) {
            Log.i(TAG, "changeColor: " + this + ";" + params);
            applySkin();
        }
    }


    @Override
    public void setTextColor(ColorStateList colors) {
        if (supportTextState != null) {
            int[][] states = colors.getStates();
            int[] colorArray = new int[states.length];
            for (int i = 0; i < states.length; i++) {
                int[] state = states[i];
                int oldColor = colors.getColorForState(state, 0);
                if (bitColor.containAttr(state, supportTextState)) {
                    colorArray[i] = mixColor(oldColor, bitColor.getColorArray(defaultLayer)[0]);
                } else {
                    colorArray[i] = oldColor;
                }
            }
            colors = new ColorStateList(states, colorArray);
        }
        super.setTextColor(colors);
    }


    private int mixColor(int oldColor, int newColor) {
        int oldR = Color.red(oldColor);
        int oldG = Color.green(oldColor);
        int oldB = Color.blue(oldColor);

        int newA = Color.alpha(newColor);
        int newR = Color.red(newColor);
        int newG = Color.green(newColor);
        int newB = Color.blue(newColor);

        newA = 255 - (255 - newA) * 2;
        if (newA <= 0) {
            return Color.argb(Math.abs(newA), oldR, oldG, oldB);
        }
        return Color.argb(newA, newR, newG, newB);
    }


    @Override
    public void setBackground(Drawable background) {
        if (isSupportBackground && bitColor.hasColorParams()) {
            background = bitColor.createDrawable(background, defaultLayer, mAngle, null, supportBackgroundState);
        }
        super.setBackground(background);
    }

    @Override
    public void setBackgroundDrawable(Drawable background) {
        if (isSupportBackground && bitColor.hasColorParams()) {
            background = bitColor.createDrawable(background, defaultLayer, mAngle, null, supportBackgroundState);
        }
        super.setBackgroundDrawable(background);
    }

}
